package com.scap.dfs.dao.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.hibernate.Transaction;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.transform.Transformers;
import org.hibernate.type.BigDecimalType;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.scap.dfs.dao.DailyCalFormulaDao;
import com.scap.dfs.dao.TrnDailyDao;
import com.scap.dfs.model.DailyCalFormula;
import com.scap.dfs.model.DailyCalFormulaConfig;
import com.scap.dfs.model.Department;
import com.scap.dfs.model.TrnDaily;
import com.scap.dfs.model.TrnDailyPK;

@Repository
public class TrnDailyDaoImpl implements TrnDailyDao {

	
	final static Logger logger = Logger.getLogger(TrnDailyDaoImpl.class);
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Autowired
	DailyCalFormulaDao formulaDao;

	@Override
	public List<TrnDaily> getList(String hospitalCode,String beginDate, String endDate) {
		Session session = sessionFactory.openSession();
		
		
//		List<DailyCalFormula> calFormulas = formulaDao.getListByHospitalCodeOrderByFlowNumber(hospitalCode);
//		List<String> listOfColumnName = new ArrayList<String>();
//		
//		for(DailyCalFormula d:calFormulas){
//			if(d.getVar1ColumnName()!=null){
//				listOfColumnName.add("trn."+d.getVar1ColumnName());
//			}
//			if(d.getVar2ColumnName()!=null){
//				listOfColumnName.add("trn."+d.getVar2ColumnName());
//			}
//			if(d.getVar3ColumnName()!=null){
//				listOfColumnName.add("trn."+d.getVar3ColumnName());
//			}
//		}
//		
//		HashSet hs = new HashSet();
//		hs.addAll(listOfColumnName);
//		listOfColumnName.clear();
//		listOfColumnName.addAll(hs);
//		String col = listOfColumnName.get(0);
//		for(int i=1;i<=listOfColumnName.size()-1;i++){
//			String s = listOfColumnName.get(i);
//			col = col+","+s;
//		}
//		col = col+",trn.INVOICE_TYPE,trn.ADMISSION_TYPE_CODE,trn.AMOUNT_AFT_DISCOUNT";
		
		
		
		
		
		List<Object[]> rows = session.createSQLQuery(""
				+"		SELECT 				                "
				+" t.HOSPITAL_CODE							"
				+" ,t.INVOICE_NO                            "
				+" ,t.INVOICE_DATE                          "
				+" ,t.RECEIPT_NO                            "
				+" ,t.RECEIPT_DATE                          "
				+" ,t.TRANSACTION_DATE                      "
				+" ,t.HN_NO                                 "
				+" ,t.PATIENT_NAME                          "
				+" ,t.EPISODE_NO                            "
				+" ,t.NATIONALITY_CODE                      "
				+" ,t.NATIONALITY_DESCRIPTION               "
				+" ,t.PAYOR_OFFICE_CODE                     "
				+" ,t.PAYOR_OFFICE_NAME                     "
				+" ,t.TRANSACTION_MODULE                    "
				+" ,t.TRANSACTION_TYPE                      "
				+" ,t.PAYOR_OFFICE_CATEGORY_CODE            "
				+" ,t.PAYOR_OFFICE_CATEGORY_DESCRIPTION     "
				+" ,t.IS_WRITE_OFF                          "
				+" ,t.LINE_NO                               "
				+" ,t.ADMISSION_TYPE_CODE                   "
				+" ,t.PATIENT_DEPARTMENT_CODE               "
				+" ,t.PATIENT_LOCATION_CODE                 "
				+" ,t.RECEIPT_DEPARTMENT_CODE               "
				+" ,t.RECEIPT_LOCATION_CODE                 "
				+" ,t.DOCTOR_DEPARTMENT_CODE                "
				+" ,t.ORDER_ITEM_CODE                       "
				+" ,t.ORDER_ITEM_DESCRIPTION                "
				+" ,t.DOCTOR_CODE                           "
				+" ,t.VERIFY_DATE                           "
				+" ,t.VERIFY_TIME                           "
				+" ,t.DOCTOR_EXECUTE_CODE                   "
				+" ,t.EXECUTE_DATE                          "
				+" ,t.EXECUTE_TIME                          "
				+" ,t.DOCTOR_RESULT_CODE                    "
				+" ,t.OLD_DOCTOR_CODE                       "
				+" ,t.RECEIPT_TYPE_CODE                     "
				+" ,t.AMOUNT_BEF_DISCOUNT                   "
				+" ,t.AMOUNT_OF_DISCOUNT                    "
				+" ,t.AMOUNT_AFT_DISCOUNT                   "
				+" ,t.AMOUNT_BEF_WRITE_OFF                  "
				+" ,t.INV_IS_VOID                           "
				+" ,t.REC_IS_VOID                           "
				+" ,t.UPDATE_DATE                           "
				+" ,t.UPDATE_TIME                           "
				+" ,t.USER_ID                               "
				+" ,t.BATCH_NO                              "
				+" ,t.YYYY                                  "
				+" ,t.MM                                    "
				+" ,t.DD                                    "
				+" ,t.NOR_ALLOCATE_AMT                      "
				+" ,t.NOR_ALLOCATE_PCT                      "
				+" ,t.DR_AMT                                "
				+" ,t.OLD_DR_AMT                            "
				+" ,t.TAX_TYPE_CODE                         "
				+" ,t.DR_PREMIUM                            "
				+" ,t.GUARANTEE_PAID_AMT                    "
				+" ,t.GUARANTEE_AMT                         "
				+" ,t.GUARANTEE_CODE                        "
				+" ,t.GUARANTEE_DR_CODE                     "
				+" ,t.GUARANTEE_TYPE                        "
				+" ,t.GUARANTEE_DATE_TIME                   "
				+" ,t.GUARANTEE_TERM_MM                     "
				+" ,t.GUARANTEE_TERM_YYYY                   "
				+" ,t.GUARANTEE_NOTE                        "
				+" ,t.IS_GUARANTEE                          "
				+" ,t.HP_AMT                                "
				+" ,t.HP_PREMIUM                            "
				+" ,t.HP_TAX                                "
				+" ,t.COMPUTE_DAILY_DATE                    "
				+" ,t.COMPUTE_DAILY_TIME                    "
				+" ,t.COMPUTE_DAILY_USER_ID                 "
				+" ,d.DOCTOR_CATEGORY_CODE                  "
				+" ,t.EXCLUDE_TREATMENT                     "
				+" ,t.PREMIUM_CHARGE_PCT                    "
				+" ,t.PREMIUM_REC_AMT                       "
				+" ,t.ACTIVE                                "
				+" ,t.INVOICE_TYPE                          "
				+" ,t.TOTAL_BILL_AMOUNT                     "
				+" ,t.TOTAL_DR_REC_AMOUNT                   "
				+" ,t.OLD_AMOUNT                            "
				+" ,t.PAY_BY_CASH                           "
				+" ,t.PAY_BY_AR                             "
				+" ,t.PAY_BY_DOCTOR                         "
				+" ,t.PAY_BY_PAYOR                          "
				+" ,t.PAY_BY_CASH_AR                        "
				+" ,t.IS_PAID                               "
				+" ,t.ORDER_ITEM_ACTIVE                     "
				+" ,r.ORDER_ITEM_CATEGORY_CODE              "
				+" ,t.WRITE_OFF_BILL_AMT                    "
				+" ,t.WRITE_OFF_RECEIPT_AMT                 "
				+" ,t.OLD_DR_AMT_BEF_WRITE_OFF              "
				+" ,t.DR_AMT_BEF_WRITE_OFF                  "
				+" ,t.DR_PREMIUM_BEF_WRITE_OFF              "
				+" ,t.HP_AMT_BEF_WRITE_OFF                  "
				+" ,t.HP_PREMIUM_WRITE_OFF                  "
				+" ,t.OLD_TAX_AMT                           "
				+" ,t.DR_TAX_406_BEF_WRITE_OFF              "
				+" ,t.TAX_FROM_ALLOCATE                     "
				+" ,t.IS_GUARANTEE_FROM_ALLOC               "
				+" ,t.IS_ONWARD                             "
				+" ,t.IS_PARTIAL                            "
				+" ,t.DR_AMT_BEF_PARTIAL                    "
				+" ,t.DR_TAX_BEF_PARTIAL                    "
				+" ,t.AMT_BEF_PARTIAL                       "
				+" ,t.IS_DISCHARGE_SUMMARY                  "
				+" ,t.DOCTOR_PRIVATE_CODE                   "
				+" ,t.NOTE                                  "
				+" ,d.DEPARTMENT_CODE						"				
				+"  FROM TRN_DAILY t left outer join DOCTOR d                                   "
				+"  on t.DOCTOR_CODE = d.CODE and t.HOSPITAL_CODE = d.HOSPITAL_CODE             "
				+"  left outer join ORDER_ITEM r on t.ORDER_ITEM_CODE = r.CODE                  "
				+"  and t.HOSPITAL_CODE = r.HOSPITAL_CODE                                       "
				+"  where "
				+"  (t.COMPUTE_DAILY_DATE is null or t.COMPUTE_DAILY_DATE like '') "
				+"  and t.HOSPITAL_CODE = '"+hospitalCode+"' 									"
				+"  and t.TRANSACTION_DATE >= '"+beginDate+"' and t.TRANSACTION_DATE <= '"+endDate+"'   "
				+"  and t.ACTIVE = '1'															"
				+" ")
				.addScalar("HOSPITAL_CODE",                    StringType.INSTANCE)
				.addScalar("INVOICE_NO",                       StringType.INSTANCE)				                                   
				.addScalar("INVOICE_DATE",                     StringType.INSTANCE)				                                   
				.addScalar("RECEIPT_NO",                       StringType.INSTANCE)				                                   
				.addScalar("RECEIPT_DATE",                     StringType.INSTANCE)				                                   
				.addScalar("TRANSACTION_DATE",                 StringType.INSTANCE)				                                   
				.addScalar("HN_NO",                            StringType.INSTANCE)				                                   
				.addScalar("PATIENT_NAME",                     StringType.INSTANCE)				                                   
				.addScalar("EPISODE_NO",                       StringType.INSTANCE)				                                   
				.addScalar("NATIONALITY_CODE",                 StringType.INSTANCE)				                                   
				.addScalar("NATIONALITY_DESCRIPTION",          StringType.INSTANCE)				                                   
				.addScalar("PAYOR_OFFICE_CODE",                StringType.INSTANCE)				                                   
				.addScalar("PAYOR_OFFICE_NAME",                StringType.INSTANCE)				                                   
				.addScalar("TRANSACTION_MODULE",               StringType.INSTANCE)			                                   
				.addScalar("TRANSACTION_TYPE",                 StringType.INSTANCE)			                                   
				.addScalar("PAYOR_OFFICE_CATEGORY_CODE",       StringType.INSTANCE)				                                   
				.addScalar("PAYOR_OFFICE_CATEGORY_DESCRIPTION",StringType.INSTANCE)				                                   
				.addScalar("IS_WRITE_OFF",                     StringType.INSTANCE)				                                   
				.addScalar("LINE_NO",                          StringType.INSTANCE)				                                   
				.addScalar("ADMISSION_TYPE_CODE",              StringType.INSTANCE)				                                   
				.addScalar("PATIENT_DEPARTMENT_CODE",          StringType.INSTANCE)				                                   
				.addScalar("PATIENT_LOCATION_CODE",            StringType.INSTANCE)				                                   
				.addScalar("RECEIPT_DEPARTMENT_CODE",          StringType.INSTANCE)				                                   
				.addScalar("RECEIPT_LOCATION_CODE",            StringType.INSTANCE)				                                   
				.addScalar("DOCTOR_DEPARTMENT_CODE",           StringType.INSTANCE)				                                   
				.addScalar("ORDER_ITEM_CODE",                  StringType.INSTANCE)				                                   
				.addScalar("ORDER_ITEM_DESCRIPTION",           StringType.INSTANCE)				                                   
				.addScalar("DOCTOR_CODE",                      StringType.INSTANCE)				                                   
				.addScalar("VERIFY_DATE",                      StringType.INSTANCE)				                                   
				.addScalar("VERIFY_TIME",                      StringType.INSTANCE)				                                   
				.addScalar("DOCTOR_EXECUTE_CODE",              StringType.INSTANCE)				                                   
				.addScalar("EXECUTE_DATE",                     StringType.INSTANCE)				                                   
				.addScalar("EXECUTE_TIME",                     StringType.INSTANCE)				                                   
				.addScalar("DOCTOR_RESULT_CODE",               StringType.INSTANCE)				                                   
				.addScalar("OLD_DOCTOR_CODE",                  StringType.INSTANCE)				                                   
				.addScalar("RECEIPT_TYPE_CODE",                StringType.INSTANCE)				                                   
				.addScalar("AMOUNT_BEF_DISCOUNT",              BigDecimalType.INSTANCE)			                                   
				.addScalar("AMOUNT_OF_DISCOUNT",               BigDecimalType.INSTANCE)			                                   
				.addScalar("AMOUNT_AFT_DISCOUNT",              BigDecimalType.INSTANCE)			                                   
				.addScalar("AMOUNT_BEF_WRITE_OFF",             BigDecimalType.INSTANCE)			                                   
				.addScalar("INV_IS_VOID",                      StringType.INSTANCE)			                                   
				.addScalar("REC_IS_VOID",                      StringType.INSTANCE)			                                   
				.addScalar("UPDATE_DATE",                      StringType.INSTANCE)			                                   
				.addScalar("UPDATE_TIME",                      StringType.INSTANCE)			                                   
				.addScalar("USER_ID",                          StringType.INSTANCE)			                                   
				.addScalar("BATCH_NO",                         StringType.INSTANCE)			                                   
				.addScalar("YYYY",                             StringType.INSTANCE)				                                   
				.addScalar("MM",                               StringType.INSTANCE)			                                   
				.addScalar("DD",                               StringType.INSTANCE)
				.addScalar("NOR_ALLOCATE_AMT",                 StringType.INSTANCE)
				.addScalar("NOR_ALLOCATE_PCT",                 BigDecimalType.INSTANCE)
				.addScalar("DR_AMT",                           BigDecimalType.INSTANCE)
				.addScalar("OLD_DR_AMT",                       BigDecimalType.INSTANCE)
				.addScalar("TAX_TYPE_CODE",                    StringType.INSTANCE)
				.addScalar("DR_PREMIUM",                       BigDecimalType.INSTANCE)
				.addScalar("GUARANTEE_PAID_AMT",               BigDecimalType.INSTANCE)
				.addScalar("GUARANTEE_AMT",                    BigDecimalType.INSTANCE)
				.addScalar("GUARANTEE_CODE",                   StringType.INSTANCE)
				.addScalar("GUARANTEE_DR_CODE",                StringType.INSTANCE)
				.addScalar("GUARANTEE_TYPE",                   StringType.INSTANCE)
				.addScalar("GUARANTEE_DATE_TIME",              StringType.INSTANCE)
				.addScalar("GUARANTEE_TERM_MM",                StringType.INSTANCE)
				.addScalar("GUARANTEE_TERM_YYYY",              StringType.INSTANCE)
				.addScalar("GUARANTEE_NOTE",                   StringType.INSTANCE)
				.addScalar("IS_GUARANTEE",                     StringType.INSTANCE)
				.addScalar("HP_AMT",                           BigDecimalType.INSTANCE)
				.addScalar("HP_PREMIUM",                       BigDecimalType.INSTANCE)
				.addScalar("HP_TAX",                           BigDecimalType.INSTANCE)
				.addScalar("COMPUTE_DAILY_DATE",               StringType.INSTANCE)
				.addScalar("COMPUTE_DAILY_TIME",               StringType.INSTANCE)
				.addScalar("COMPUTE_DAILY_USER_ID",            StringType.INSTANCE)
				.addScalar("DOCTOR_CATEGORY_CODE",             StringType.INSTANCE)
				.addScalar("EXCLUDE_TREATMENT",                StringType.INSTANCE)
				.addScalar("PREMIUM_CHARGE_PCT",               StringType.INSTANCE)
				.addScalar("PREMIUM_REC_AMT",                  BigDecimalType.INSTANCE)
				.addScalar("ACTIVE",                           StringType.INSTANCE)
				.addScalar("INVOICE_TYPE",                     StringType.INSTANCE)
				.addScalar("TOTAL_BILL_AMOUNT",                BigDecimalType.INSTANCE)
				.addScalar("TOTAL_DR_REC_AMOUNT",              BigDecimalType.INSTANCE)
				.addScalar("OLD_AMOUNT",                       BigDecimalType.INSTANCE)
				.addScalar("PAY_BY_CASH",                      StringType.INSTANCE)
				.addScalar("PAY_BY_AR",                        StringType.INSTANCE)
				.addScalar("PAY_BY_DOCTOR",                    StringType.INSTANCE)
				.addScalar("PAY_BY_PAYOR",                     StringType.INSTANCE)
				.addScalar("PAY_BY_CASH_AR",                   StringType.INSTANCE)
				.addScalar("IS_PAID",                          StringType.INSTANCE)
				.addScalar("ORDER_ITEM_ACTIVE",                StringType.INSTANCE)
				.addScalar("ORDER_ITEM_CATEGORY_CODE",         StringType.INSTANCE)
				.addScalar("WRITE_OFF_BILL_AMT",               BigDecimalType.INSTANCE)
				.addScalar("WRITE_OFF_RECEIPT_AMT",            BigDecimalType.INSTANCE)
				.addScalar("OLD_DR_AMT_BEF_WRITE_OFF",         BigDecimalType.INSTANCE)
				.addScalar("DR_AMT_BEF_WRITE_OFF",             BigDecimalType.INSTANCE)
				.addScalar("DR_PREMIUM_BEF_WRITE_OFF",         BigDecimalType.INSTANCE)
				.addScalar("HP_AMT_BEF_WRITE_OFF",             BigDecimalType.INSTANCE)
				.addScalar("HP_PREMIUM_WRITE_OFF",             BigDecimalType.INSTANCE)
				.addScalar("OLD_TAX_AMT",                      BigDecimalType.INSTANCE)
				.addScalar("DR_TAX_406_BEF_WRITE_OFF",         BigDecimalType.INSTANCE)
				.addScalar("TAX_FROM_ALLOCATE",                StringType.INSTANCE)
				.addScalar("IS_GUARANTEE_FROM_ALLOC",          StringType.INSTANCE)
				.addScalar("IS_ONWARD",                        StringType.INSTANCE)
				.addScalar("IS_PARTIAL",                       StringType.INSTANCE)
				.addScalar("DR_AMT_BEF_PARTIAL",               BigDecimalType.INSTANCE)
				.addScalar("DR_TAX_BEF_PARTIAL",               BigDecimalType.INSTANCE)
				.addScalar("AMT_BEF_PARTIAL",                  BigDecimalType.INSTANCE)
				.addScalar("IS_DISCHARGE_SUMMARY",             StringType.INSTANCE)
				.addScalar("DOCTOR_PRIVATE_CODE",              StringType.INSTANCE)
				.addScalar("NOTE",                             StringType.INSTANCE)
				.addScalar("DEPARTMENT_CODE",                  StringType.INSTANCE)
				.list();
		
		
		
		List<TrnDaily> result = new ArrayList<TrnDaily>();
		
		for(Object[] row : rows){
			TrnDailyPK pk = new TrnDailyPK();
			pk.setHospitalCode(row[0].toString());
			pk.setInvoiceDate(row[2].toString());
			pk.setInvoiceNo(row[1].toString());
			pk.setInvoiceType(row[76].toString());
			pk.setLineNo(row[18].toString());
			pk.setReceiptDate(row[4].toString());
			pk.setTransactionDate(row[5].toString());
			
			TrnDaily trn = new TrnDaily();
			trn.setId(pk);
			trn.setDoctorCode(row[27].toString());
			trn.setDoctorCategoryCode(row[71]!=null?row[71].toString():"");
			trn.setOrderItemCode(row[25].toString());
			trn.setOrderItemCategoryCode(row[87]!=null?row[87].toString():"");
			trn.setPayorOfficeCode(row[11]!=null?row[11].toString():"");
			trn.setAdmissionTypeCode(row[19].toString());
			trn.setAmountAftDiscount(new BigDecimal(row[38].toString()));
			trn.setDoctorDepartmentCode(row[107]!=null?row[107].toString():"");
			
			result.add(trn);
		}
		
		
		session.close();
		return result;
	}
	
	@Override
	public String getAttributeNameByColumnName(String columnName) {
		
		AbstractEntityPersister aep=((AbstractEntityPersister)sessionFactory.getClassMetadata(TrnDaily.class));  
		String[] properties=aep.getPropertyNames();  
		try{
			for(int nameIndex=0;nameIndex!=properties.length;nameIndex++){  
	//			   System.out.println("Property name: "+properties[nameIndex]);  
				   String[] columns=aep.getPropertyColumnNames(nameIndex);  
				   for(int columnIndex=0;columnIndex!=columns.length;columnIndex++){  
					  if(columns[columnIndex].equals(columnName)||columns[columnIndex]==columnName){
						  return properties[nameIndex];
					  }
	//			      System.out.println("Column name: "+columns[columnIndex]);  
				   }  
				} 
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		
		return null;
	}

	@Override
	public boolean updateTrnDailyList(List<TrnDaily> trnDailyList) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		try{						
			for(TrnDaily trnDaily: trnDailyList){
				session.update(trnDaily);
			}			
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public int countGetList(String hospitalCode, String beginDate,
			String endDate) {
		Session session = sessionFactory.openSession();
		int result= ((Long)session.createQuery(
				"select count(*) from TrnDaily t where t.id.transactionDate >= '"+beginDate+"' "
				+ " and t.id.transactionDate <= '"+endDate+"' and t.id.hospitalCode = '"+hospitalCode+"' "
				+ " and (t.computeDailyDate is null or t.computeDailyDate like '' )  "
				+ " and t.active = '1' ").uniqueResult()).intValue();
		session.close();
		return result;
	}

	
	@Override
	public String updateTrnDailyForBasicAllocateProcess(TrnDaily trnDailyOld) {
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		DateFormat timeFormat = new SimpleDateFormat("HHmmss");
		Date date = new Date();
		
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			
			TrnDaily trnDaily = (TrnDaily) session.get(TrnDaily.class, trnDailyOld.getId());
			
			//Set update data info
			trnDaily.setUpdateDate(dateFormat.format(date).toString());
			trnDaily.setUpdateTime(timeFormat.format(date).toString());
			trnDaily.setUserId(trnDailyOld.getUserId());
			
			//Set compute data info
			trnDaily.setComputeDailyDate(dateFormat.format(date).toString());
			trnDaily.setComputeDailyTime(timeFormat.format(date).toString());
			trnDaily.setComputeDailyUserId(trnDailyOld.getUserId());
			
			//Set DoctorCategory
			trnDaily.setDoctorCategoryCode(trnDailyOld.getDoctorCategoryCode());
			
			//Set OrderCategory
			trnDaily.setOrderItemCategoryCode(trnDailyOld.getOrderItemCategoryCode());
			
			//Set taxType
			trnDaily.setTaxTypeCode(trnDailyOld.getTaxTypeCode());
			
			//Set DoctorTaxAmt
			BigDecimal value1 = trnDailyOld.getDoctorTaxAmt();
			BigDecimal result1 = value1.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
			trnDaily.setDoctorTaxAmt(result1);
			
			
			//Set DrAmt
			BigDecimal value2 = trnDailyOld.getDrAmt();
			BigDecimal result2 = value2.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
			trnDaily.setDrAmt(result2);
			
			//Set formulaId
			trnDaily.setBasicAllocateFormulaId(trnDailyOld.getBasicAllocateFormulaId());
			
			//Set hpAmt
			trnDaily.setHpAmt(trnDailyOld.getHpAmt());
			
			//Set DoctorDepartmentCode
			trnDaily.setDoctorDepartmentCode(trnDailyOld.getDoctorDepartmentCode());
			
			//Set NorAllocateAmt
			BigDecimal value3 = trnDailyOld.getNorAllocateAmt();
			BigDecimal result3 = value3.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
			trnDaily.setNorAllocateAmt(result3);
			
			//Set NorAllocatePct
			BigDecimal value4 = trnDailyOld.getNorAllocatePct();
			BigDecimal result4 = value4.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
			trnDaily.setNorAllocatePct(result4);
			
			//Set TaxFromAllocate
			trnDaily.setTaxFromAllocate(trnDailyOld.getTaxFromAllocate());
			
			//Set IsGuarantee
			trnDaily.setIsGuarantee(trnDailyOld.getIsGuarantee());
			
			//Set IsGuaranteeFromAllocate
			trnDaily.setIsGuaranteeFromAlloc(trnDailyOld.getIsGuaranteeFromAlloc());
			
			
			
			session.update(trnDaily);
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return e.toString();
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return "success";
	}

	@Override
	public String rollbackBasicAllocate(String hospitalCode, String beginDate,
			String endDate, String userId) {
		
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		DateFormat timeFormat = new SimpleDateFormat("HHmmss");
		Date date = new Date();
		
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		try{
			
			String updateDate = dateFormat.format(date).toString();
			String updateTime = timeFormat.format(date).toString();
			
			int rowUpdate = session.createQuery("update TrnDaily t set t.drAmt = 0.00,t.computeDailyDate = '',t.computeDailyTime = '',	"
					+ "t.computeDailyUserId = '',t.updateDate = '"+updateDate+"',t.updateTime = '"+updateTime+"'"
					+ ",t.userId = '"+userId+"',t.taxTypeCode ='',t.hpAmt=0.00,t.doctorDepartmentCode=''"
					+ ",t.norAllocateAmt=0.00 ,t.norAllocatePct=0.00 ,t.doctorTaxAmt=0.00,t.taxFromAllocate=''"
					+ ",t.isGuarantee='',t.isGuaranteeFromAlloc='' "
					+"  where "
					+"  t.id.hospitalCode = '"+hospitalCode+"' and t.id.transactionDate >= '"+beginDate+"' "
					+ " and t.id.transactionDate <= '"+endDate+"' "
					).executeUpdate();
			
			tx.commit();
			session.close();
			return "success";
		}
		catch(Exception e){
			logger.error(e);
			return e.toString();
		}
	}

	
	
	
}
